import { useEffect } from 'react'
import { FIELD_RULES } from '@/utils/RegExps'
import { Input, Button, Form } from 'antd-mobile'
import { observer, useLocalObservable } from 'mobx-react'
import NavBar from '@/components/Global/NavBar'
import styles from './index.module.less'
import { useLocation } from 'umi'
import Store from './store'
import type { UpdateUserInfoParamsType } from '../api/interface'

type TitleMap = Record<
    string,
    {
        title: string
        maxLength: number
    }
>
const TITLE_MAP: TitleMap = {
    phone: {
        title: '手机号',
        maxLength: 11,
    },
    idcard: {
        title: '身份证号',
        maxLength: 18,
    },
    realname: {
        title: '姓名',
        maxLength: 15,
    },
}

export default observer(() => {
    const {
        state,
        query: { type },
    } = useLocation()
    const { updateData } = useLocalObservable(() => new Store())
    const [form] = Form.useForm()

    useEffect(() => {
        console.log(type, state)
        form.setFieldValue(type, state?.value)
    }, [])

    const title = TITLE_MAP[(type as unknown) as string].title
    const maxLength = TITLE_MAP[(type as unknown) as string].maxLength

    const onSubmit = (value: UpdateUserInfoParamsType) => {
        updateData(value)
    }

    const settingRules = () => {
        if (type === 'phone') {
            return [{ required: true, message: '手机号必填' }, FIELD_RULES.PHONE]
        } else if (type === 'idcard') {
            return [{ required: true, message: '身份证号必填' }, FIELD_RULES.ID_CARD]
        } else {
            // if (type === 'realname')
            return [{ required: true, message: '姓名必填' }, FIELD_RULES.NAME]
        }
    }

    return (
        <div className={styles.page}>
            <NavBar title={title} />
            <div className={styles.content}>
                <Form
                    style={{ '--border-top': 'none' }}
                    onFinish={onSubmit}
                    form={form}
                    requiredMarkStyle="text-optional"
                    footer={
                        <Button block type="submit" className={styles.submitBtn}>
                            保存
                        </Button>
                    }
                >
                    <Form.Item name={type} rules={settingRules()}>
                        <Input
                            className={styles.inputView}
                            placeholder={`请输入${title}`}
                            maxLength={maxLength}
                            clearable
                        />
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
})
